#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include "RingQueue.hpp"

struct thread_data
{
    RingQueue<int> *rq;
    std::string name;
};

void *consumer(void *args)
{
    thread_data *td = static_cast<thread_data *>(args);
    // RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    while (true)
    {
        sleep(3);
        int t = 0;
        td->rq->Pop(&t); // 出队

        std::cout << td->name << " 消费者拿到了一个：" << t << std::endl;
    }
}

    int data = 1;

void *productor(void *args)
{
    thread_data *td = static_cast<thread_data *>(args);
    // RingQueue<int> *rq = static_cast<RingQueue<int> *>(args);
    while (true)
    {
        sleep(1);
        std::cout << td->name << " 生产了一个数据:" << data << std::endl;

        td->rq->Equeue(data);
        data++;
    }
}

int main()
{
    // 申请阻塞队列
    RingQueue<int> *rq = new RingQueue<int>();

    // 构建生产消费
    pthread_t p[3], c[2];

    thread_data *td = new thread_data();
    td->rq = rq;
    td->name = "pthread-1";
    pthread_create(p, nullptr, productor, td);

    thread_data *td2 = new thread_data();
    td2->rq = rq;
    td2->name = "pthread-2";
    pthread_create(p + 1, nullptr, productor, td2);

    thread_data *td3 = new thread_data();
    td3->rq = rq;
    td3->name = "pthread-3";
    pthread_create(p + 2, nullptr, productor, td3);

    thread_data *td4 = new thread_data();
    td4->rq = rq;
    td4->name = "cthread-1";
    pthread_create(c, nullptr, consumer, td4);

    thread_data *td5 = new thread_data();
    td5->rq = rq;
    td5->name = "cthread-2";
    pthread_create(c + 1, nullptr, consumer, td5);

    pthread_join(p[0], nullptr);
    pthread_join(c[0], nullptr);
    pthread_join(p[1], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(p[2], nullptr);
    return 0;
}

// void *consumer(void *args)
// {
//     BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
//     while (true)
//     {
//         //sleep(1);
//         Task t = bq->Pop(); // 出队
//         t.Execute();
//         // int data = bq->Pop(); // 出队
//         std::cout << "消费了一个任务" << t.X() << "+" << t.Y() << "=" << t.Result() << std::endl;
//     }
// }

// void *productor(void *args)
// {
//     int x = 1;
//     int y = 1;
//     BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
//     while (true)
//     {
//         sleep(1);
//         std::cout << "生产了一个任务" << x << "+" << y << "=?" << std::endl;
//         Task t(x, y);
//         bq->Equeue(t); // 入队
//         x++;
//         y++;
//     }
// }

// int main()
// {
//     // 申请阻塞队列
//     BlockQueue<int> *bq = new BlockQueue<int>();

//     // 构建生产消费
//     pthread_t p, c;

//     pthread_create(&p, nullptr, productor, bq);
//     pthread_create(&c, nullptr, consumer, bq);

//     pthread_join(p, nullptr);
//     pthread_join(c, nullptr);
// }